﻿using AutoMapper;
using MediatR;
using Newtonsoft.Json;
using S.Common.EditReproductivePresenceStateHelper;
using S.Common.EditWanderStateHelper;
using S.Common.Enums.Archives;
using S.Common.Enums.PregnancyTest;
using S.Common.helper;
using S.PregnancyTest.API.Application.Command;
using S.PregnancyTest.API.Dto;
using S.PregnancyTest.Domain;
using S.PregnancyTest.Domain.Model;
using S.PregnancyTest.Infrastructure.Interface;

namespace S.PregnancyTest.API.Application.CommandHandlers
{
    public class PregnancyTestCreateHandler : IRequestHandler<PregnancyTestCreateCommand, bool>
    {

        private readonly IPregnancyTestRepository repository;

        private readonly MyDbContext dbContext;

        private readonly IMapper mapper;

        private readonly IHttpContextAccessor httpContextAccessor;

        private readonly IConfiguration configuration;

        public PregnancyTestCreateHandler(IPregnancyTestRepository repository, IMapper mapper, MyDbContext dbContext, IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            this.repository = repository;
            this.mapper = mapper;
            this.dbContext = dbContext;
            this.httpContextAccessor = httpContextAccessor;
            this.configuration = configuration;
        }

        /// <summary>
        /// 异步添加种母妊检信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> Handle(PregnancyTestCreateCommand request, CancellationToken cancellationToken)
        {

            //使用事物
            using (var tran = dbContext.Database.BeginTransaction())
            {
                try
                {
                    string Gateway = configuration.GetValue<string>("Gateway");

                    #region 添加妊检信息
                    //使用automapper传值
                    var pregnancyTest = mapper.Map<PregnancyTestModel>(request.addPregnancyTestDto);
                    pregnancyTest.CreateDate = DateTime.Now; //创建时间赋值为当前时间
                    pregnancyTest.UpdateDate = null;         //修改时间赋值为空
                    pregnancyTest.AuditTime = null;          //审核时间赋值为空

                    //执行添加妊检方法
                    await repository.AddAsync(pregnancyTest);

                    #endregion

                    #region 反填并修改种母历史记录

                    request.editBreed.EarTag = pregnancyTest.EarTag;

                    //反填种母历史记录
                    var jsonString = HttpClientHelper.PostResponseKey($"{Gateway}/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", request.editBreed);
                    //将获取到的种母历史记录序列化
                    var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);

                    if (string.IsNullOrWhiteSpace(jsonString))
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    //修改种母历史记录
                    response.PregnancyDate = pregnancyTest.PregnancyDate; //修改妊检日期
                    response.PregnancytestResult = Convert.ToInt32(pregnancyTest.PregnancytestResult); //修改妊检结果
                    response.IsEditor = pregnancyTest.PregnancytestResult == PregnancytestResultEnum.怀孕 ? true : false;//根据种母的妊检状态来更改是否可编辑的状态
                    response.UpdateBy = pregnancyTest.CreateBy;
                    //修改种母历史记录
                    var breeding = HttpClientHelper.PutDataResponse($"{Gateway}/bhset/api/BreedHistory/UpdateBreedingHistory", response);

                    if (breeding == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    #endregion

                    #region 添加转舍信息

                    request.transferDto.EarTag = pregnancyTest.EarTag;
                    request.transferDto.SurrenderDate = pregnancyTest.PregnancyDate; //转舍时间为妊检时间
                    //跨服务调用添加转舍接口
                    var transfer = HttpClientHelper.PostResponse($"{Gateway}/transset/api/TransFer/CreateSheepTransFer", request.transferDto);

                    if (transfer == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    #endregion

                    #region 修改档案信息

                    //获取到妊检结果
                    var result = pregnancyTest.PregnancytestResult;
                    var UState = 0;

                    //根据妊检结果改变不同的繁殖状态
                    switch (result)
                    {
                        case (PregnancytestResultEnum)1:
                            UState = 5;
                            break;
                        case (PregnancytestResultEnum)2:
                            UState = 2;
                            break;
                        case (PregnancytestResultEnum)3:
                            UState = 4;
                            break;
                        case (PregnancytestResultEnum)4:
                            UState = 7;
                            break;
                        case (PregnancytestResultEnum)5:
                            UState = 3;
                            break;
                    }

                    var archives = EditReproductivePresenceState.UpdateReproductivePresenceState(pregnancyTest.EarTag, 1, UState, pregnancyTest.PregnancyDate, Gateway);
                    if (archives == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }
                    #endregion

                    #region 修改流转状态

                    var WanderReproductiveState = 0;

                    switch (result)
                    {
                        case (PregnancytestResultEnum)1:
                            WanderReproductiveState = 2;
                            break;
                        case (PregnancytestResultEnum)2:
                            WanderReproductiveState = 2;
                            break;
                        case (PregnancytestResultEnum)3:
                            WanderReproductiveState = 2;
                            break;
                        case (PregnancytestResultEnum)4:
                            WanderReproductiveState = 3;
                            break;
                        case (PregnancytestResultEnum)5:
                            WanderReproductiveState = 2;
                            break;
                    }

                    EditWanderState.EditWander(pregnancyTest.EarTag, WanderReproductiveState, Gateway);

                    #endregion

                    #region 修改配种状态

                    var breed = HttpClientHelper.PostResponse($"{Gateway}/BreedSet/api/MaternalMating/UpdateState?ear=" + pregnancyTest.EarTag + "", "");

                    #endregion

                    #region 添加生产记录

                    WanderCreateDto wander = new WanderCreateDto
                    {
                        WanderId = 0,
                        EarTag = pregnancyTest.EarTag,
                        WanderReproductiveState = (WanderReproductiveStateEnum)3,
                        Content = pregnancyTest.PregnancytestResult == (PregnancytestResultEnum)4 ? "类型：怀孕" : "类型：返情",
                        WanderDate = pregnancyTest.PregnancyDate,
                        SerialNumber = pregnancyTest.SerialNumber,
                    };

                    var wand = HttpClientHelper.PostResponse($"{Gateway}/achs/api/Wander/WanderCreate", wander);

                    if (wand == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    #endregion


                    //事物执行
                    tran.Commit();

                    return true;
                }
                catch (Exception)
                {
                    //事物回滚
                    tran.Rollback();

                    return false;
                }
            }

        }

    }
}
